package sort; /**
 * @author spf
 * @date 2024/5/1
 * @time 21:52
 */

import java.util.Arrays;


/**
 * 二分查找
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] values = {1, 21, 12, 35, 45, 20, 2, 6, 7, 9};
        System.out.println("原始数组：" + Arrays.toString(values));
        int searchWord = 20;
        int i = binarySearch(values, searchWord);
        System.out.println(i);
    }

    private static int binarySearch(int[] values, int searchWord) {
        int low = 0;
        int high = values.length - 1;
        Arrays.sort(values);
        System.out.println(Arrays.toString(values));
        while (low <= high) {
            int mid = (low + high) / 2;
            System.out.println(mid);
            if (values[mid] == searchWord) {
                return mid;
            }
            if (values[mid] > searchWord) {
                high = mid - 1;
            }

            if (values[mid] < searchWord) {
                low = mid + 1;
            }
        }
        return -1;
    }
}
